package com.example.springbootjackson.controller;

import com.example.springbootjackson.model.Order;
import com.example.springbootjackson.model.Response;
import com.example.springbootjackson.requestContext.RequestContext;
import com.example.springbootjackson.traceId.MDCRunnable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.Executors;

@RestController
@Slf4j
@RequestMapping("/test")
public class TestHeaderController {

    private final ObjectMapper objectMapper = new ObjectMapper();


    @PostMapping("/testHeader")
    public String testHeader() {
        log.info("threadName={}", Thread.currentThread().getName());
        Integer userId = RequestContext.getUserId();
        log.info("userId={}", userId);
        return "ok";
    }

    @PostMapping("/testResp")
    public Response<Order> testResp() throws JsonProcessingException {
        log.info("测试testResp");
        Order order = new Order();
        order.setCreateDate(new Date());
        Response<Order> resp = new Response();
        resp.setData(order);
        log.info("测试testResp  resp={}", objectMapper.writeValueAsString(resp));
        if (true) {
            throw new RuntimeException("运行时异常");
        }
//        System.out.println(3/0);
        return resp;
    }

    @PostMapping("/testResp2")
    public Response<Order> testResp2() throws JsonProcessingException {
        log.info("测试testResp");
        Order order = new Order();
        order.setCreateDate(new Date());
        Response<Order> resp = new Response();
        resp.setData(order);
        log.info("测试testResp  resp={}", objectMapper.writeValueAsString(resp));
//        Executors.newSingleThreadExecutor().execute(() -> {
//            try {
//                log.info("测试响应 resp={}", objectMapper.writeValueAsString(resp));
//            } catch (JsonProcessingException e) {
//                e.printStackTrace();
//            }
//        });
        Executors.newSingleThreadExecutor().execute(new MDCRunnable(
                () -> {
                    try {
                        log.info("测试响应 resp={}", objectMapper.writeValueAsString(resp));
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                }
        ));
        return resp;
    }

}
